/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.niclun.projectwebshop.nbp;

import edu.chl.niclun.projectwebshop.nbp.DataBase.Database;
import edu.chl.niclun.projectwebshop.nbp.Entities.Client;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

/**
 *Controllerbean for register.xhtml
 * @author martin
 */
@ManagedBean(name="RegisterControllerBean")
@RequestScoped
public class RegisterControllerBean {

    @ManagedProperty(value="#{RegisterBackingBean}")
    private RegisterBackingBean registerBean;
    
    private boolean navigate = false;
    
    /** Creates a new instance of RegisterControllerBean */
    public RegisterControllerBean() {
    }

    public RegisterBackingBean getRegisterBean() {
        return registerBean;
    }

    public void setRegisterBean(RegisterBackingBean registerBean) {
        this.registerBean = registerBean;
    }
    //tries to register a user to the database
    public void registerUser(ActionEvent evt){
        //make a query in the email
        List<Client> clients = Database.getWebshopController().getClient(registerBean.getEmail());
        //if the querylist is emty the email is not used with another client
        if(clients.isEmpty()){
            Client client = new Client(registerBean.getEmail(),registerBean.getPassword());
            client.setFname(registerBean.getFname());
            client.setLname(registerBean.getLname());
            Database.getWebshopController().addClient(client);
            navigate = true;
        }
        //if the email is registered with another client, show error message
        else
             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid Email", "This Email have already been registered"));
    }
    
    
    //navigate
    public String navigate(){
        if(navigate){
            navigate = !navigate;
            return "login";
        }
        else
            return "register";
        
    }
    
}
